﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;
using TimeLineControlNamedPipes;
using TimeLineControlNamedPipes.Communication;
using TimeLineDataContract;
using System.Linq;

namespace TimeLineControl
{
    public partial class FrmTimeLine : Form
    {

        #region Fields

        private readonly int _maxHeight;
        private TimeSpan _elapseTime;
        private readonly ReceiverPipe _pipePowerPoint;
        private bool _isLoad;
        private int _countPolling;
        private bool _lastStatusConnectionOk;
        private bool _runningShowPresentation;
        private bool _pauseUpdatetimeBar;
        private bool _waitResponseDesk;
        private bool _sendStartPresentation;
        private bool _cmdStartPresentation;

        private DockWindows _barCurrentShowPos = DockWindows.Top;
        private bool _barCurrentShowFullScreen;

        #endregion

        #region Form Events

        public FrmTimeLine()
        {

            InitializeComponent();

            TimerPresentationShow.Stop();

            scrollingAlert.ScrollOn = false;

            var path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\TimeLineControl";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            var filename = string.Concat(path, @"\TimelineControl.config");

            if (File.Exists(filename))
            {
                var fields = typeof(DataConfigTimeLine).GetProperties(BindingFlags.Static | BindingFlags.Public);
                var stream = File.Open(filename, FileMode.Open, FileAccess.Read);
                var bformatter = new BinaryFormatter();
                var result = (Dictionary<string, object>)bformatter.Deserialize(stream);
                stream.Close();
                stream.Dispose();
                try
                {
                    foreach (var field in fields)
                    {
                        field.SetValue(null, result[field.Name], null);
                    }
                }
                catch (Exception)
                {
                    File.Delete(filename);
                }
            }

            _maxHeight = timeLineProgressBar.Height + LblCurrentBalance.Height + 3;
            LblRemainingTime.Text = DataConfigTimeLine.TotalTimeLine.ToString();
            LblCurrentTime.Text = DateTime.Now.ToLongTimeString();
            timeLineProgressBar.Minimum = 0;
            timeLineProgressBar.Maximum = (int)DataConfigTimeLine.TotalTimeLine.TotalSeconds;
            timeLineProgressBar.Value = 0;

            //START NETPIPE RECEIVER
            _pipePowerPoint = new ReceiverPipe("TimeLineControl");
            _pipePowerPoint.ServiceOn(PipeService.UriControl);
            _pipePowerPoint.PowerPointChangeName += PowerPointChangeName;
            _pipePowerPoint.TimeLineShowbar += TimeLineShowbar;
            _pipePowerPoint.SlidesDeckReady += ResponseSlidesDeck;
            _pipePowerPoint.SlideShowRunning += ReceiveStatusShowSlideRunning;
            _pipePowerPoint.SlideChange += ResponseSlidesChange;

            namePipeToolStripMenuItem.Text = string.Empty;
            namePPTToolStripMenuItem.Text = string.Empty;
            qtdSlidesToolStripMenuItem.Text = string.Empty;
            totalTimeToolStripMenuItem.Text = string.Empty;

            alignTopToolStripMenuItem.Checked = (DataConfigTimeLine.AlignBar == DockWindows.Top);
            alignInBottomToolStripMenuItem.Checked = (DataConfigTimeLine.AlignBar == DockWindows.Bottom);
            fullScreenToolStripMenuItem.Checked = DataConfigTimeLine.FullScreen;
            hideTimelineBarToolStripMenuItem.Checked = !DataConfigTimeLine.TimeLineBarVisibled;

            showUpdateSlidesFromPowerPointToolStripMenuItem.Checked = DataConfigTimeLine.ShowUpdatePowerPoint;
            foreach (ToolStripMenuItem menu in pollingConnectionToolStripMenuItem.DropDownItems)
            {
                menu.Checked = (menu.Tag.ToString() == DataConfigTimeLine.PowerPointPolling.ToString());
            }

            openRecentPresentationToolStripMenuItem.DropDownItems.Clear();
            var delindex = new List<int>();
            for (int index = 0; index < DataConfigTimeLine.LastFullPathPresentationRun.Count; index++)
            {
                if (DataConfigTimeLine.LastFullPathPresentationRun[index] != string.Empty)
                {
                    if (File.Exists(DataConfigTimeLine.LastFullPathPresentationRun[index]))
                    {
                        var menu = new ToolStripMenuItem
                        {
                            Text = DataConfigTimeLine.LastNamePresentationRun[index],
                            ToolTipText = DataConfigTimeLine.LastFullPathPresentationRun[index],
                            AutoToolTip = true
                        };
                        openRecentPresentationToolStripMenuItem.DropDownItems.Add(menu);
                        menu.Click += OpenPresentationMenuCLick;
                    }
                    else
                    {
                        delindex.Add(index);
                    }
                }
            }
            foreach (var i in delindex)
            {
                DataConfigTimeLine.LastNamePresentationRun.RemoveAt(i);
                DataConfigTimeLine.LastFullPathPresentationRun.RemoveAt(i);
            }
            openRecentPresentationToolStripMenuItem.Enabled =
                (openRecentPresentationToolStripMenuItem.DropDownItems.Count > 0);
        }

        private void FrmTimeLine_Load(object sender, EventArgs e)
        {
            SetColors();
            Height = timeLineProgressBar.Height;
            this.SetDockWindows(DataConfigTimeLine.AlignBar, Height, DataConfigTimeLine.FullScreen);
            notifyIcon.ShowBalloonTip(500, ScreenUtil.StringResource("NameApp"), ScreenUtil.StringResource("Welcome"), ToolTipIcon.Info);
            _isLoad = true;


            //START TIMER TO CONNECT AND KEEP ALIVE TO POWERPOINT AND STATUS TIMELINE BAR
            SetMenuConnect(false);
            _lastStatusConnectionOk = false;
            timerCheckConnection.Interval = 100;
            timerCheckConnection.Start();
            ResetTimePresenattion(false);
        }

        private void FrmTimeLine_VisibleChanged(object sender, EventArgs e)
        {
            if (_isLoad)
            {
                if (Visible && !DataConfigTimeLine.TimeLineBarVisibled)
                {
                    Visible = false;
                }
            }
        }

        private void FrmTimeLine_FormClosing(object sender, FormClosingEventArgs e)
        {
            var cur = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;

            #region stop timer

            timerCheckConnection.Stop();
            TimerPresentationShow.Stop();

            #endregion

            #region pipe release

            _pipePowerPoint.PowerPointChangeName += PowerPointChangeName;
            _pipePowerPoint.TimeLineShowbar -= TimeLineShowbar;
            _pipePowerPoint.SlidesDeckReady -= ResponseSlidesDeck;
            _pipePowerPoint.SlideShowRunning -= ReceiveStatusShowSlideRunning;
            _pipePowerPoint.SlideChange -= ResponseSlidesChange;
            _pipePowerPoint.ServiceOff();
            _pipePowerPoint.Dispose();

            #endregion

            #region save config

            DataConfigTimeLine.TotalTimeLine = new TimeSpan(0, 60, 0);
            DataConfigTimeLine.PowerPointApplication = string.Empty;
            DataConfigTimeLine.PowerPointConnected = false;
            DataConfigTimeLine.SlidesDesk = new SlideDeskContract[] { };
            DataConfigTimeLine.CurrentSlide = null;

            var path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\TimeLineControl";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            var filename = string.Concat(path, @"\TimelineControl.config");
            var fields = typeof(DataConfigTimeLine).GetProperties(BindingFlags.Static | BindingFlags.Public);
            var values = fields.ToDictionary(value => value.Name, value => value.GetValue(null, null));
            var stream = File.Open(filename, FileMode.OpenOrCreate, FileAccess.Write);
            var bformatter = new BinaryFormatter();
            bformatter.Serialize(stream, values);

            stream.Close();
            stream.Dispose();

            #endregion

            Cursor.Current = cur;
        }

        private void TimeLineProgressBarMouseEnter(object sender, EventArgs e)
        {
            if (scrollingAlert.Visible)
            {
                scrollingAlert.Visible = false;
                scrollingAlert.ScrollOn = false;
                PanelShowFull(false);
                return;
            } 
            PanelShowFull(true);
        }



        private void PanelShow_MouseLeave(object sender, EventArgs e)
        {
            scrollingAlert.Visible = false;
            scrollingAlert.ScrollOn = false;
            PanelShowFull(false);
        }
        
        private void ScrollingAlertMouseEnter(object sender, EventArgs e)
        {
            scrollingAlert.Visible = false;
            scrollingAlert.ScrollOn = false;
            PanelShowFull(false);
        }

        private void ScrollingAlertTextScroolEnd(object sender, EventArgs args)
        {
            if (scrollingAlert.Visible)
            {
                scrollingAlert.Visible = false;
                scrollingAlert.ScrollOn = false;
                PanelShowFull(false);
            }
        }

        #endregion

        #region Menu Events

        private static void OpenPresentationMenuCLick(object sender, EventArgs e)
        {
            OpenPresentation(((ToolStripMenuItem)sender).ToolTipText, ProcessWindowStyle.Maximized);
        }

        private void SlideDesckItemMenuCLick(object sender, EventArgs e)
        {
            var id = long.Parse(((ToolStripMenuItem)sender).Tag.ToString());

            var result = DataConfigTimeLine.SlidesDesk.FirstOrDefault(s => s.Id == id);
            if (result != null)
            {
                if (!DataConfigTimeLine.PowerPointConnected)
                {
                    foreach (ToolStripMenuItem menuopen in openRecentPresentationToolStripMenuItem.DropDownItems)
                    {
                        if (menuopen.Text == DataConfigTimeLine.PowerPointApplication)
                        {
                            OpenPresentation(menuopen.ToolTipText, ProcessWindowStyle.Minimized);
                            _cmdStartPresentation = true;
                            break;
                        }
                    }
                }
                DataConfigTimeLine.CurrentSlide = result;
                if (!_cmdStartPresentation)
                {
                    SendStartShowPResentation(DataConfigTimeLine.CurrentSlide);
                    _sendStartPresentation = true;
                }
            }
        }

        private void ExitToolStripMenuItemClick(object sender, EventArgs e)
        {
            Close();
        }

        private void AlertsToolStripMenuItemClick(object sender, EventArgs e)
        {
            var frm = new FrmConfigAlert();
            if (TimerPresentationShow.Enabled)
            {
                _pauseUpdatetimeBar = true;
            }
            frm.ShowDialog();
            if (TimerPresentationShow.Enabled)
            {
                _pauseUpdatetimeBar = false;
            }
        }

        private void AboutToolStripMenuItemClick(object sender, EventArgs e)
        {
            var frm = new FrmAboutBox();
            if (TimerPresentationShow.Enabled)
            {
                _pauseUpdatetimeBar = true;
            }
            frm.ShowDialog();
            if (TimerPresentationShow.Enabled)
            {
                _pauseUpdatetimeBar = false;
            }
        }

        private void ColorToolStripMenuItemClick(object sender, EventArgs e)
        {
            var frm = new FrmConfigColor();
            if (TimerPresentationShow.Enabled)
            {
                _pauseUpdatetimeBar = true;
            }
            frm.ShowDialog();
            if (TimerPresentationShow.Enabled)
            {
                _pauseUpdatetimeBar = false;
            }
            SetColors();
        }

        private void HideTimelineBarToolStripMenuItemClick(object sender, EventArgs e)
        {
            ChangeHideTimelineBar();
        }

        private void ResetTimeToolStripMenuItemClick(object sender, EventArgs e)
        {
            var result = MessageBox.Show(ScreenUtil.StringResource("ResetTimer"), ScreenUtil.StringResource("NameApp"), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
            if (result == DialogResult.Yes)
            {
                ResetTimePresenattion(false);
                hideTimelineBarToolStripMenuItem.Checked = true;
                ChangeHideTimelineBar();
                SetMenuConnect(DataConfigTimeLine.PowerPointConnected);
                _sendStartPresentation = false;
            }
        }

        private void ImportSlideDeckToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var cur = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;
            ImportSlideDeck();
            Cursor.Current = cur;
        }

        private void FullScreenToolStripMenuItemClick(object sender, EventArgs e)
        {
            DataConfigTimeLine.FullScreen = fullScreenToolStripMenuItem.Checked;
            ChangeDock();
        }

        private void LastSlideShowToolStripMenuItemClick(object sender, EventArgs e)
        {
            if (DataConfigTimeLine.SlidesDesk.Length > 0 && DataConfigTimeLine.CurrentSlide != null)
            {
                if (!DataConfigTimeLine.PowerPointConnected)
                {
                    foreach (ToolStripMenuItem menuopen in openRecentPresentationToolStripMenuItem.DropDownItems)
                    {
                        if (menuopen.Text == DataConfigTimeLine.PowerPointApplication)
                        {
                            OpenPresentation(menuopen.ToolTipText, ProcessWindowStyle.Minimized);
                            _cmdStartPresentation = true;
                            break;
                        }
                    }
                }
                if (!_cmdStartPresentation)
                {
                    SendStartShowPResentation(DataConfigTimeLine.CurrentSlide);
                    _sendStartPresentation = true;
                }
            }
        }

        private void PreviousSlideShowToolStripMenuItemClick(object sender, EventArgs e)
        {
            if (DataConfigTimeLine.SlidesDesk.Length > 0 && DataConfigTimeLine.CurrentSlide != null)
            {
                if (DataConfigTimeLine.CurrentSlide.SlideNumber - 1 >= 1)
                {
                    if (!DataConfigTimeLine.PowerPointConnected)
                    {
                        foreach (ToolStripMenuItem menuopen in openRecentPresentationToolStripMenuItem.DropDownItems)
                        {
                            if (menuopen.Text == DataConfigTimeLine.PowerPointApplication)
                            {
                                OpenPresentation(menuopen.ToolTipText, ProcessWindowStyle.Minimized);
                                _cmdStartPresentation = true;
                                break;
                            }
                        }
                    }
                    DataConfigTimeLine.CurrentSlide = DataConfigTimeLine.SlidesDesk[DataConfigTimeLine.CurrentSlide.SlideNumber - 2];
                    if (!_cmdStartPresentation)
                    {
                        SendStartShowPResentation(DataConfigTimeLine.CurrentSlide);
                        _sendStartPresentation = true;
                    }
                }
            }
        }

        private void NextSlideShowToolStripMenuItemClick(object sender, EventArgs e)
        {
            if (DataConfigTimeLine.SlidesDesk.Length > 0 && DataConfigTimeLine.CurrentSlide != null)
            {
                if (DataConfigTimeLine.SlidesDesk.Length >= DataConfigTimeLine.CurrentSlide.SlideNumber + 1)
                {
                    if (!DataConfigTimeLine.PowerPointConnected)
                    {
                        foreach (ToolStripMenuItem menuopen in openRecentPresentationToolStripMenuItem.DropDownItems)
                        {
                            if (menuopen.Text == DataConfigTimeLine.PowerPointApplication)
                            {
                                OpenPresentation(menuopen.ToolTipText, ProcessWindowStyle.Minimized);
                                _cmdStartPresentation = true;
                                break;
                            }
                        }
                    }
                    DataConfigTimeLine.CurrentSlide = DataConfigTimeLine.SlidesDesk[DataConfigTimeLine.CurrentSlide.SlideNumber +1];
                    if (!_cmdStartPresentation)
                    {
                        SendStartShowPResentation(DataConfigTimeLine.CurrentSlide);
                        _sendStartPresentation = true;
                    }
                }
            } 
        }

        private void StartToolStripMenuItemClick(object sender, EventArgs e)
        {
            if (DataConfigTimeLine.SlidesDesk.Length > 0)
            {
                SendStartShowPResentation(DataConfigTimeLine.SlidesDesk[0]);
                _sendStartPresentation = true;
            }
        }

        private void ContextMenuStripOpening(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (TimerPresentationShow.Enabled)
            {
                _pauseUpdatetimeBar = true;
            }
        }

        private void ContextMenuStripClosed(object sender, ToolStripDropDownClosedEventArgs e)
        {
            if (TimerPresentationShow.Enabled)
            {
                _pauseUpdatetimeBar = false;
            }
        }

        private void ShowUpdateSlidesFromPowerPointToolStripMenuItemClick(object sender, EventArgs e)
        {
            DataConfigTimeLine.ShowUpdatePowerPoint = showUpdateSlidesFromPowerPointToolStripMenuItem.Checked;
        }

        private void AlignTopToolStripMenuItemClick(object sender, EventArgs e)
        {
            PanelShow.Visible = false;
            Height = timeLineProgressBar.Height;
            DataConfigTimeLine.AlignBar = DockWindows.Top;
            alignInBottomToolStripMenuItem.Checked = !alignTopToolStripMenuItem.Checked;
            ChangeDock();
        }

        private void AlignInBottomToolStripMenuItemClick(object sender, EventArgs e)
        {
            PanelShow.Visible = false;
            Height = timeLineProgressBar.Height;
            DataConfigTimeLine.AlignBar = DockWindows.Bottom;
            alignTopToolStripMenuItem.Checked = !alignInBottomToolStripMenuItem.Checked;
            ChangeDock();
        }

        private void PollingtoolStripMenuItemClick(object sender, EventArgs e)
        {
            DataConfigTimeLine.PowerPointPolling = int.Parse(((ToolStripMenuItem)sender).Tag.ToString());
            foreach (ToolStripMenuItem menu in pollingConnectionToolStripMenuItem.DropDownItems)
            {
                menu.Checked = (menu.Tag.ToString() == DataConfigTimeLine.PowerPointPolling.ToString());
            }
        }

        #endregion

        #region NETPIPE RECEIVER

        private void PowerPointChangeName(string newPptName)
        {
            var splitname = newPptName.Split(Convert.ToChar(1));
            if (splitname[1] != string.Empty)
            {
                if (DataConfigTimeLine.LastFullPathPresentationRun.Count == 5)
                {
                    DataConfigTimeLine.LastFullPathPresentationRun.RemoveAt(0);
                    DataConfigTimeLine.LastNamePresentationRun.RemoveAt(0);
                    openRecentPresentationToolStripMenuItem.DropDownItems.RemoveAt(0);
                }
                if (!DataConfigTimeLine.LastFullPathPresentationRun.Exists(f => f == splitname[1]))
                {
                    DataConfigTimeLine.LastFullPathPresentationRun.Add(splitname[1]);
                    DataConfigTimeLine.LastNamePresentationRun.Add(splitname[0]);
                    var menu = new ToolStripMenuItem
                    {
                        Text = splitname[0],
                        ToolTipText = splitname[1],
                        AutoToolTip = true
                    };
                    openRecentPresentationToolStripMenuItem.DropDownItems.Add(menu);
                    menu.Click += OpenPresentationMenuCLick;
                }
                openRecentPresentationToolStripMenuItem.Enabled =
                    (openRecentPresentationToolStripMenuItem.DropDownItems.Count > 0);
            }
            if (DataConfigTimeLine.PowerPointApplication != splitname[0])
            {
                DataConfigTimeLine.PowerPointApplication = splitname[0];
                namePPTToolStripMenuItem.Text = splitname[0];
                if (splitname[0] == string.Empty)
                {
                    DataConfigTimeLine.SlidesDesk = new SlideDeskContract[] { };
                    BuildMenuSlides();
                }
                else
                {
                    notifyIcon.ShowBalloonTip(500, ScreenUtil.StringResource("NameApp"), ScreenUtil.StringResource("ConnectedIn") + " " + newPptName, ToolTipIcon.Info);
                    var cur = Cursor.Current;
                    Cursor.Current = Cursors.WaitCursor;
                    ImportSlideDeck();
                    Cursor.Current = cur;
                }
            }
        }

        private void TimeLineShowbar(bool show)
        {
            Visible = show;
            DataConfigTimeLine.TimeLineBarVisibled = Visible;
            hideTimelineBarToolStripMenuItem.Checked = !Visible;
        }

        private void ResponseSlidesDeck(SlideDeskContract[] response)
        {
            if (TimerPresentationShow.Enabled) return;
            if (response == null)
            {
                response = new SlideDeskContract[] { };
            }
            DataConfigTimeLine.SlidesDesk = response;
            BuildMenuSlides();
            if (_waitResponseDesk || DataConfigTimeLine.ShowUpdatePowerPoint)
            {
                _waitResponseDesk = false;
                notifyIcon.ShowBalloonTip(500, ScreenUtil.StringResource("NameApp"), string.Format(ScreenUtil.StringResource("ResponseSlides"), DataConfigTimeLine.SlidesDesk.Length), ToolTipIcon.Info);
            }
        }

        private void ReceiveStatusShowSlideRunning(bool running)
        {
            _runningShowPresentation = running;
            if (running && !TimerPresentationShow.Enabled)
            {
                notifyIcon.ShowBalloonTip(500, ScreenUtil.StringResource("NameApp"), ScreenUtil.StringResource("MsgPresRunning"), ToolTipIcon.Warning);
            }
            if (_runningShowPresentation)
            {
                if (_sendStartPresentation)
                {
                    hideTimelineBarToolStripMenuItem.Checked = false;
                    Visible = true;
                    DataConfigTimeLine.TimeLineBarVisibled = Visible;
                }
                else
                {
                    DataConfigTimeLine.CurrentSlide = null;
                    hideTimelineBarToolStripMenuItem.Checked = true;
                    Visible = false;
                    DataConfigTimeLine.TimeLineBarVisibled = Visible;
                }
            }
            SetMenuConnect(true);
        }

        private void ResponseSlidesChange(SlideDeskContract response)
        {
            if (!_runningShowPresentation) return;
            DataConfigTimeLine.CurrentSlide = _sendStartPresentation ? response : null;
        }

        #endregion

        #region Methods and Function

        private static void OpenPresentation(string file,ProcessWindowStyle style)
        {
            var index = file.LastIndexOf("\\");
            var path = file.Substring(0, index);
            var startInfo = new ProcessStartInfo
            {
                FileName = file,
                CreateNoWindow = true,
                UseShellExecute = true,
                WorkingDirectory = path,
                WindowStyle = style
                 
            };
            Process.Start(startInfo);
        }

        private void ChangeHideTimelineBar()
        {
            Visible = !hideTimelineBarToolStripMenuItem.Checked;
            DataConfigTimeLine.TimeLineBarVisibled = Visible;
            if (DataConfigTimeLine.PowerPointConnected)
            {
                try
                {
                    //SEND TO POWERPOINT STATUS TIMELINE BAR
                    SenderPipe.SendPowerPointShowBar(DataConfigTimeLine.TimeLineBarVisibled, DataConfigTimeLine.PowerPointPipeName);
                }
                catch
                {
                    notifyIcon.ShowBalloonTip(500, ScreenUtil.StringResource("NameApp"), ScreenUtil.StringResource("LostConnect"), ToolTipIcon.Error);
                    DataConfigTimeLine.PowerPointConnected = false;
                    SetMenuConnect(false);
                }
            }
        }

        private void BuildMenuSlides()
        {
            SlideDeckToolStripMenuItem.DropDownItems.Clear();
            var label = ScreenUtil.StringResource("SlideMenu");
            if (DataConfigTimeLine.SlidesDesk.Length != 0)
            {
                label += " (" + DataConfigTimeLine.SlidesDesk.Length + ")";
            }
            SlideDeckToolStripMenuItem.Text = label;
            var tm = new TimeSpan();
            for (int index = 0; index < DataConfigTimeLine.SlidesDesk.Length; index++)
            {
                var itemMenu = DataConfigTimeLine.SlidesDesk[index];
                var menu = new ToolStripMenuItem { Text = string.Format("{0} - {1}", index + 1, itemMenu.Title), Tag = itemMenu.Id };
                tm = tm.Add(itemMenu.ElaspTime);
                SlideDeckToolStripMenuItem.DropDownItems.Add(menu);
                menu.Click += SlideDesckItemMenuCLick;
            }

            qtdSlidesToolStripMenuItem.Visible = true;
            totalTimeToolStripMenuItem.Visible = true;
            qtdSlidesToolStripMenuItem.Text = label;
            totalTimeToolStripMenuItem.Text = tm.ToString("c");
            DataConfigTimeLine.TotalTimeLine = tm;
        }

        private void SetColors()
        {
            BackColor = DataConfigTimeLine.FormBackGroundColor;
            timeLineProgressBar.BackColor = DataConfigTimeLine.FormBackGroundColor;
            LblRemainingTime.BackColor = DataConfigTimeLine.FormBackGroundColor;
            LblCurrentTime.BackColor = DataConfigTimeLine.FormBackGroundColor;
            LblCurrentBalance.BackColor = DataConfigTimeLine.FormBackGroundColor;
            LblRemainingTime.ForeColor = DataConfigTimeLine.FormTextColorInboundColor;
            LblCurrentTime.ForeColor = DataConfigTimeLine.FormTextColorInboundColor;
            LblCurrentBalance.ForeColor = DataConfigTimeLine.FormTextColorInboundColor;
            timeLineProgressBar.ForeColor = DataConfigTimeLine.ProgressBarInboundColor;
            scrollingAlert.BackColor = DataConfigTimeLine.AlertBackGroundColor;
            scrollingAlert.ForeColor = DataConfigTimeLine.AlertTextColor;
        }

        private void ChangeDock()
        {
            PanelShow.Visible = false;
            Height = timeLineProgressBar.Height; this.SetDockWindows(DataConfigTimeLine.AlignBar, Height, DataConfigTimeLine.FullScreen);
            _barCurrentShowPos = DataConfigTimeLine.AlignBar;
            _barCurrentShowFullScreen = DataConfigTimeLine.FullScreen;
        }

        private void SetDockShow(DockWindows postion, bool fullscreen)
        {
            this.SetDockWindows(postion, Height, fullscreen);
            _barCurrentShowPos = postion;
            _barCurrentShowFullScreen = fullscreen;
        }

        private void SetMenuConnect(bool connected)
        {
            if (connected)
            {
                notifyIcon.Icon = Properties.Resources.TimeLine;
                StatusConnectionToolStripMenuItem.Text = ScreenUtil.StringResource("InfConnection");
            }
            else
            {
                notifyIcon.Icon = Properties.Resources.TimeLineOFF;
                StatusConnectionToolStripMenuItem.Text = ScreenUtil.StringResource("WaitConnection");
            }
            namePipeToolStripMenuItem.Text = ScreenUtil.StringResource("ConnectionName") + @" " + DataConfigTimeLine.PowerPointPipeName;

            namePipeToolStripMenuItem.Visible = connected;

            startToolStripMenuItem.Enabled = connected;

            ImportSlideDeckToolStripMenuItem.Enabled = connected;

            foreach (var item in StatusConnectionToolStripMenuItem.DropDownItems)
            {
                ((ToolStripLabel)item).Visible = connected;
            }


            if (_runningShowPresentation)
            {
                openRecentPresentationToolStripMenuItem.Enabled = false;
                StatusConnectionToolStripMenuItem.Enabled = false;
                startToolStripMenuItem.Enabled = false;
                resetTimeToolStripMenuItem.Enabled = true;
                ImportSlideDeckToolStripMenuItem.Enabled = false;
                resetTimeToolStripMenuItem.Enabled = false;
                hideTimelineBarToolStripMenuItem.Enabled = false;
                lastSlideShowToolStripMenuItem.Enabled = false;
                previousSlideShowToolStripMenuItem.Enabled = false;
                nextSlideShowToolStripMenuItem.Enabled = false;
                SlideDeckToolStripMenuItem.Enabled = false;
                foreach (var item in SlideDeckToolStripMenuItem.DropDownItems)
                {
                    ((ToolStripMenuItem)item).Visible = false;
                }
                hideTimelineBarToolStripMenuItem.Enabled = true;
                fullScreenToolStripMenuItem.Enabled = false;
                alignTopToolStripMenuItem.Enabled = false;
                alignInBottomToolStripMenuItem.Enabled = false;
            }
            else
            {
                openRecentPresentationToolStripMenuItem.Enabled = !TimerPresentationShow.Enabled;
                SlideDeckToolStripMenuItem.Enabled = (DataConfigTimeLine.CurrentSlide != null);
                foreach (var item in SlideDeckToolStripMenuItem.DropDownItems)
                {
                    ((ToolStripMenuItem)item).Visible = (DataConfigTimeLine.CurrentSlide != null);
                }
                lastSlideShowToolStripMenuItem.Enabled = (DataConfigTimeLine.CurrentSlide != null);
                nextSlideShowToolStripMenuItem.Enabled = (DataConfigTimeLine.CurrentSlide != null && DataConfigTimeLine.SlidesDesk.Length >= DataConfigTimeLine.CurrentSlide.SlideNumber + 1);
                previousSlideShowToolStripMenuItem.Enabled = (DataConfigTimeLine.CurrentSlide != null && DataConfigTimeLine.CurrentSlide.SlideNumber - 1 >= 1);
                if (TimerPresentationShow.Enabled)
                {
                    startToolStripMenuItem.Enabled = false;
                    resetTimeToolStripMenuItem.Enabled = true;
                    resetTimeToolStripMenuItem.Enabled = true;
                }
                else
                {
                    startToolStripMenuItem.Enabled = connected;
                    resetTimeToolStripMenuItem.Enabled = false;
                    resetTimeToolStripMenuItem.Enabled = false;
                    DataConfigTimeLine.CurrentSlide = null;
                }
                StatusConnectionToolStripMenuItem.Enabled = true;
                hideTimelineBarToolStripMenuItem.Enabled = true;
                fullScreenToolStripMenuItem.Enabled = true;
                alignTopToolStripMenuItem.Enabled = true;
                alignInBottomToolStripMenuItem.Enabled = true;
            }
        }

        private void ImportSlideDeck()
        {
            try
            {
                SenderPipe.SendPowerPointSlidesDesk(DataConfigTimeLine.PowerPointPipeName);
                notifyIcon.ShowBalloonTip(500, ScreenUtil.StringResource("NameApp"), ScreenUtil.StringResource("WaitSlides"), ToolTipIcon.Info);
                _waitResponseDesk = true;
            }
            catch
            {
                notifyIcon.ShowBalloonTip(500, ScreenUtil.StringResource("NameApp"), ScreenUtil.StringResource("LostConnect"), ToolTipIcon.Error);
                DataConfigTimeLine.PowerPointConnected = false;
                SetMenuConnect(false);
            }
        }

        private void PanelShowFull(bool all)
        {
            if (all)
            {
                if (TimerPresentationShow.Enabled && DataConfigTimeLine.CurrentSlide != null)
                {
                    if (DataConfigTimeLine.CurrentSlide.DockPosition == DockWindows.Top)
                    {
                        PanelShow.Visible = true;
                        Height = _maxHeight;
                    }
                    else if (DataConfigTimeLine.CurrentSlide.DockPosition == DockWindows.Bottom)
                    {
                        PanelShow.Visible = true;
                        Height = _maxHeight;
                        var sr = Screen.PrimaryScreen.Bounds;
                        if (DataConfigTimeLine.CurrentSlide.FullScreen)
                        {
                            Top = sr.Height - Height;
                        }
                        else
                        {
                            Top = Screen.PrimaryScreen.WorkingArea.Height - Height;
                        }
                    }
                }
                else
                {
                    if (DataConfigTimeLine.AlignBar == DockWindows.Top)
                    {
                        PanelShow.Visible = true;
                        Height = _maxHeight;
                    }
                    else if (DataConfigTimeLine.AlignBar == DockWindows.Bottom)
                    {
                        PanelShow.Visible = true;
                        Height = _maxHeight;
                        var sr = Screen.PrimaryScreen.Bounds;
                        if (DataConfigTimeLine.FullScreen)
                        {
                            Top = sr.Height - Height;
                        }
                        else
                        {
                            Top = Screen.PrimaryScreen.WorkingArea.Height - Height;
                        }
                    }
                }
            }
            else
            {
                if (TimerPresentationShow.Enabled && DataConfigTimeLine.CurrentSlide != null)
                {
                    if (DataConfigTimeLine.CurrentSlide.DockPosition == DockWindows.Top)
                    {
                        PanelShow.Visible = false;
                        Height = timeLineProgressBar.Height;
                    }
                    else if (DataConfigTimeLine.CurrentSlide.DockPosition == DockWindows.Bottom)
                    {
                        PanelShow.Visible = false;
                        Height = timeLineProgressBar.Height;
                        var sr = Screen.PrimaryScreen.Bounds;
                        if (DataConfigTimeLine.CurrentSlide.FullScreen)
                        {
                            Top = sr.Height - Height;
                        }
                        else
                        {
                            Top = Screen.PrimaryScreen.WorkingArea.Height - Height;
                        }
                    }
                }
                else
                {
                    if (DataConfigTimeLine.AlignBar == DockWindows.Top)
                    {
                        PanelShow.Visible = false;
                        Height = timeLineProgressBar.Height;
                    }
                    else if (DataConfigTimeLine.AlignBar == DockWindows.Bottom)
                    {
                        PanelShow.Visible = false;
                        Height = timeLineProgressBar.Height;
                        var sr = Screen.PrimaryScreen.Bounds;
                        if (DataConfigTimeLine.FullScreen)
                        {
                            Top = sr.Height - Height;
                        }
                        else
                        {
                            Top = Screen.PrimaryScreen.WorkingArea.Height - Height;
                        }
                    }
                }
            }
            PanelShow.Invalidate();
        }

        private static void PrepareTimeLimitsSlides()
        {
            var dtref = DateTime.Now;
            foreach (var item in DataConfigTimeLine.SlidesDesk)
            {
                item.StarTimeShow = dtref;
                item.EndTimeShow = dtref.AddTicks(item.ElaspTime.Ticks);
                dtref = dtref.AddTicks(item.ElaspTime.Ticks);
            }
        }

        private void SendStartShowPResentation(SlideDeskContract slide)
        {
            try
            {
                //SEND TO POWERPOINT STATUS TIMELINE BAR
                SenderPipe.SendPowerPointShowBar(DataConfigTimeLine.TimeLineBarVisibled, DataConfigTimeLine.PowerPointPipeName);
                try
                {
                    //SEND TO POWERPOINT SlidE to Start
                    SenderPipe.SendPowerPointCurrentSlide(slide, DataConfigTimeLine.PowerPointPipeName);
                    if (!TimerPresentationShow.Enabled)
                    {
                        //START TIME PRESENTATION
                        PrepareTimeLimitsSlides();
                        ResetTimePresenattion(true);
                    }
                }
                catch
                {
                    notifyIcon.ShowBalloonTip(500, ScreenUtil.StringResource("NameApp"), ScreenUtil.StringResource("LostConnect"), ToolTipIcon.Error);
                    DataConfigTimeLine.PowerPointConnected = false;
                    SetMenuConnect(false);
                }
            }
            catch
            {
                notifyIcon.ShowBalloonTip(500, ScreenUtil.StringResource("NameApp"), ScreenUtil.StringResource("LostConnect"), ToolTipIcon.Error);
                DataConfigTimeLine.PowerPointConnected = false;
                SetMenuConnect(false);
            }
        }

        private void ResetTimePresenattion(bool startime)
        {
            DataConfigTimeLine.CurrentSlide = null;
            foreach (var item in DataConfigTimeLine.SlidesDesk)
            {
                item.StarTimeShow = null;
                item.EndTimeShow = null;
            }
            TimerPresentationShow.Stop();
            _pauseUpdatetimeBar = false;
            _elapseTime = new TimeSpan();
            LblRemainingTime.Text = DataConfigTimeLine.TotalTimeLine.ToString();
            timeLineProgressBar.Minimum = 0;
            timeLineProgressBar.Maximum = (int)DataConfigTimeLine.TotalTimeLine.TotalSeconds;
            LblCurrentBalance.Text = @"00:00:00";
            timeLineProgressBar.Value = 0;
            if (startime)
            {
                PrepareTimeLimitsSlides();
                TimerPresentationShow.Start();
            }
        }

        #endregion

        #region timers

        private void TimerCheckConnectionTick(object sender, EventArgs e)
        {
            if (_isLoad && Visible && !DataConfigTimeLine.TimeLineBarVisibled)
            {
                return;
            }
            if (timerCheckConnection.Interval != 500)
            {
                _isLoad = false;
                timerCheckConnection.Interval = 500;
                timerCheckConnection.Start();
                return;
            }
            if (_cmdStartPresentation && DataConfigTimeLine.PowerPointConnected)
            {
                _cmdStartPresentation = false;
                SendStartShowPResentation(DataConfigTimeLine.CurrentSlide);
                _sendStartPresentation = true;
                return;
            }
            _countPolling++;
            if (_countPolling > DataConfigTimeLine.PowerPointPolling * 2)
            {
                _countPolling = 0;
            }
            if (DataConfigTimeLine.PowerPointConnected && _countPolling == 0)
            {
                try
                {
                    SenderPipe.SendPowerPointPipeOk(DataConfigTimeLine.PowerPointPipeName);
                    SenderPipe.SendPowerPointShowBar(DataConfigTimeLine.TimeLineBarVisibled, DataConfigTimeLine.PowerPointPipeName);
                    if (DataConfigTimeLine.PowerPointApplication != namePPTToolStripMenuItem.Text)
                    {
                        namePPTToolStripMenuItem.Text = DataConfigTimeLine.PowerPointApplication;
                    }
                    if (!DataConfigTimeLine.PowerPointConnected)
                    {
                        notifyIcon.ShowBalloonTip(500, ScreenUtil.StringResource("NameApp"), ScreenUtil.StringResource("RestoreConnect"), ToolTipIcon.Info);
                    }
                    DataConfigTimeLine.PowerPointConnected = true;
                    if (!_lastStatusConnectionOk)
                    {
                        SetMenuConnect(true);
                    }
                    _lastStatusConnectionOk = true;
                }
                catch
                {
                    DataConfigTimeLine.PowerPointConnected = false;
                    notifyIcon.ShowBalloonTip(500, ScreenUtil.StringResource("NameApp"), ScreenUtil.StringResource("LostConnect"), ToolTipIcon.Error);
                    namePPTToolStripMenuItem.Text = string.Empty;
                    if (_lastStatusConnectionOk)
                    {
                        SetMenuConnect(false);
                    }
                    _lastStatusConnectionOk = false;
                }

                //validate recente files
                var delindex = new List<int>();
                for (var i = 0; i < openRecentPresentationToolStripMenuItem.DropDownItems.Count; i++)
                {
                    if (!File.Exists(openRecentPresentationToolStripMenuItem.DropDownItems[i].ToolTipText))
                    {
                        DataConfigTimeLine.LastFullPathPresentationRun[i] = string.Empty;
                        DataConfigTimeLine.LastNamePresentationRun[i] = string.Empty;
                        delindex.Add(i);
                    }
                }
                foreach (var i in delindex)
                {
                    DataConfigTimeLine.LastFullPathPresentationRun.RemoveAt(i);
                    DataConfigTimeLine.LastNamePresentationRun.RemoveAt(i);
                    openRecentPresentationToolStripMenuItem.DropDownItems.RemoveAt(i);
                }
                openRecentPresentationToolStripMenuItem.Enabled =
                    (openRecentPresentationToolStripMenuItem.DropDownItems.Count > 0) && !TimerPresentationShow.Enabled;
            }
            else if (!DataConfigTimeLine.PowerPointConnected)
            {
                try
                {
                    SenderPipe.SendPowerPointPipeOk(DataConfigTimeLine.PowerPointPipeName);
                    SenderPipe.SendPowerPointShowBar(DataConfigTimeLine.TimeLineBarVisibled, DataConfigTimeLine.PowerPointPipeName);
                    if (DataConfigTimeLine.PowerPointApplication != namePPTToolStripMenuItem.Text)
                    {
                        namePPTToolStripMenuItem.Text = DataConfigTimeLine.PowerPointApplication;
                    }
                    if (DataConfigTimeLine.PowerPointApplication != string.Empty)
                    {
                        notifyIcon.ShowBalloonTip(500, ScreenUtil.StringResource("NameApp"), ScreenUtil.StringResource("RestoreConnect"), ToolTipIcon.Info);
                    }
                    DataConfigTimeLine.PowerPointConnected = true;
                    if (!_lastStatusConnectionOk)
                    {
                        SetMenuConnect(true);
                    }
                    _lastStatusConnectionOk = true;
                }
                catch
                {
                    if (_lastStatusConnectionOk)
                    {
                        SetMenuConnect(false);
                    }
                    _lastStatusConnectionOk = false;
                }
            }
        }

        private void TimerPresentationShow_Tick(object sender, EventArgs e)
        {
            _elapseTime = _elapseTime.Add(new TimeSpan(0, 0, 1));

            //alerts
            if (_elapseTime.TotalSeconds == DataConfigTimeLine.AlertTime1.TotalSeconds)
            {
                var msg = DataConfigTimeLine.AlertTime1.TotalMinutes + "min.";
                if (!string.IsNullOrEmpty(DataConfigTimeLine.MsgAlertTime1))
                {
                    msg = DataConfigTimeLine.MsgAlertTime1;
                }
                scrollingAlert.ScrollText = msg;
                scrollingAlert.Visible = true;
                PanelShowFull(true);
                scrollingAlert.ScrollOn = true;
            }
            if (_elapseTime.TotalSeconds == DataConfigTimeLine.AlertTime2.TotalSeconds)
            {
                var msg = DataConfigTimeLine.AlertTime2.TotalMinutes + "min.";
                if (!string.IsNullOrEmpty(DataConfigTimeLine.MsgAlertTime2))
                {
                    msg = DataConfigTimeLine.MsgAlertTime2;
                }
                scrollingAlert.ScrollText = msg;
                scrollingAlert.Visible = true;
                PanelShowFull(true);
                scrollingAlert.ScrollOn = true;
            }
            if (_elapseTime.TotalSeconds == DataConfigTimeLine.AlertTime3.TotalSeconds)
            {
                var msg = DataConfigTimeLine.AlertTime3.TotalMinutes + "min.";
                if (!string.IsNullOrEmpty(DataConfigTimeLine.MsgAlertTime3))
                {
                    msg = DataConfigTimeLine.MsgAlertTime3;
                }
                scrollingAlert.ScrollText = msg;
                scrollingAlert.Visible = true;
                PanelShowFull(true);
                scrollingAlert.ScrollOn = true;
            }
            if (_elapseTime.TotalSeconds == DataConfigTimeLine.AlertTime4.TotalSeconds)
            {
                var msg = DataConfigTimeLine.AlertTime4.TotalMinutes + "min.";
                if (!string.IsNullOrEmpty(DataConfigTimeLine.MsgAlertTime4))
                {
                    msg = DataConfigTimeLine.MsgAlertTime4;
                }
                scrollingAlert.ScrollText = msg;
                scrollingAlert.Visible = true;
                PanelShowFull(true);
                scrollingAlert.ScrollOn = true;
            }
            if (_elapseTime.TotalSeconds == DataConfigTimeLine.AlertTime5.TotalSeconds)
            {
                var msg = DataConfigTimeLine.AlertTime5.TotalMinutes + "min.";
                if (!string.IsNullOrEmpty(DataConfigTimeLine.MsgAlertTime5))
                {
                    msg = DataConfigTimeLine.MsgAlertTime5;
                }
                scrollingAlert.ScrollText = msg;
                scrollingAlert.Visible = true;
                PanelShowFull(true);
                scrollingAlert.ScrollOn = true;
            }

            if (_pauseUpdatetimeBar) return;

            TopMost = true;
            TopLevel = true;
            var dtref = DateTime.Now;
            var remaining = DataConfigTimeLine.TotalTimeLine.Subtract(_elapseTime);
            LblRemainingTime.Text = _elapseTime + @" / " + remaining;
            LblCurrentTime.Text = DateTime.Now.ToLongTimeString();
            if (timeLineProgressBar.Maximum >= (int)_elapseTime.TotalSeconds)
            {
                timeLineProgressBar.Value = (int)_elapseTime.TotalSeconds;
                if (DataConfigTimeLine.CurrentSlide != null)
                {
                    // ReSharper disable PossibleNullReferenceException
                    // ReSharper disable PossibleInvalidOperationException
                    var sldtm = DataConfigTimeLine.SlidesDesk.FirstOrDefault(s => s.Id == DataConfigTimeLine.CurrentSlide.Id);
                    //validate position
                    if (_barCurrentShowPos != sldtm.DockPosition || _barCurrentShowFullScreen != sldtm.FullScreen)
                    {
                        SetDockShow(sldtm.DockPosition, sldtm.FullScreen);
                    }

                    if (sldtm.EndTimeShow.Value < dtref)
                    {
                        var dif = dtref.Subtract(sldtm.EndTimeShow.Value);
                        dif = new TimeSpan(dif.Hours, dif.Minutes, dif.Seconds);
                        LblCurrentBalance.Text = dif.ToString("c");
                        if (timeLineProgressBar.ForeColor != DataConfigTimeLine.ProgressBarOutboundColorNeg)
                        {
                            timeLineProgressBar.ForeColor = DataConfigTimeLine.ProgressBarOutboundColorNeg;
                            LblCurrentBalance.ForeColor = DataConfigTimeLine.ProgressBarOutboundColorNeg;
                            timeLineProgressBar.Invalidate();
                            LblCurrentBalance.Invalidate();
                        }
                    }
                    else if (sldtm.EndTimeShow.Value >= dtref && sldtm.StarTimeShow.Value < dtref)
                    {
                        var dif = new TimeSpan();
                        LblCurrentBalance.Text = dif.ToString("c");
                        if (timeLineProgressBar.ForeColor != DataConfigTimeLine.ProgressBarInboundColor)
                        {
                            timeLineProgressBar.ForeColor = DataConfigTimeLine.ProgressBarInboundColor;
                            LblCurrentBalance.ForeColor = DataConfigTimeLine.FormTextColorInboundColor;
                            timeLineProgressBar.Invalidate();
                            LblCurrentBalance.Invalidate();
                        }
                    }
                    else if (sldtm.StarTimeShow.Value > dtref)
                    {
                        var dif = sldtm.StarTimeShow.Value.Subtract(dtref);
                        dif = new TimeSpan(dif.Hours, dif.Minutes, dif.Seconds);
                        LblCurrentBalance.Text = dif.ToString("c");
                        if (timeLineProgressBar.ForeColor != DataConfigTimeLine.ProgressBarOutboundColorPos)
                        {
                            timeLineProgressBar.ForeColor = DataConfigTimeLine.ProgressBarOutboundColorPos;
                            LblCurrentBalance.ForeColor = DataConfigTimeLine.FormTextColorInboundColor;
                            timeLineProgressBar.Invalidate();
                            LblCurrentBalance.Invalidate();
                        }
                    }
                    // ReSharper restore PossibleNullReferenceException
                    // ReSharper restore PossibleInvalidOperationException
                }
                else
                {
                    // ReSharper disable RedundantCheckBeforeAssignment
                    if (LblRemainingTime.Text != @"00:00:00")
                    {
                        LblRemainingTime.Text = @"00:00:00";
                    }
                    if (LblCurrentBalance.Text != @"00:00:00")
                    {
                        LblCurrentBalance.Text = @"00:00:00";
                    }
                    // ReSharper restore RedundantCheckBeforeAssignment
                    if (timeLineProgressBar.ForeColor != DataConfigTimeLine.ProgressBarInboundColor)
                    {
                        timeLineProgressBar.ForeColor = DataConfigTimeLine.ProgressBarInboundColor;
                        LblCurrentBalance.ForeColor = DataConfigTimeLine.FormTextColorInboundColor;
                        timeLineProgressBar.Invalidate();
                        LblCurrentBalance.Invalidate();
                    }
                }
            }
            else
            {
                if (timeLineProgressBar.ForeColor != DataConfigTimeLine.ProgressBarOutboundColorNeg)
                {
                    timeLineProgressBar.Value = timeLineProgressBar.Maximum;
                    timeLineProgressBar.ForeColor = DataConfigTimeLine.ProgressBarOutboundColorNeg;
                    LblCurrentBalance.ForeColor = DataConfigTimeLine.ProgressBarOutboundColorNeg;
                }
                LblCurrentBalance.Text = remaining.ToString();
            }
        }

        #endregion

    }
}
